package DataStructure.linear;


import java.util.Iterator;
import java.lang.Iterable;

//队列就好比贪吃蛇，每次插入都放在最后，取得时候从头开始，，栈就好比倒车入库，差的时候把头卸下来，取得是候从头的下一个取开始
public class Queue<T> implements Iterable<T>{

    private Node head;
    private int N;
    private Node last;


    public Queue(){
        this.head=new Node(null,null);
        this.N=0;
        this.last=null;
    }


    //判断是否为空
    public boolean isEmpty(){
        return N==0;
    }

    //元素个数
    public int size(){
        return N;
    }

    //从队列中插入一个元素
    public void enqueue(T t){
        Node newNode=new Node(t,null);
        //当前尾结点是空
        if(last==null){
            last=newNode;
            head.next=last;
        }else {
            Node oldlast=last;
            last=newNode;
            oldlast.next=last;
        }
        N++;
    }

    //从队列中拿出一个元素
    public T dequeue(){
        if(isEmpty()){
            return null;
        }
        Node oldfirst=head.next;
        head.next=oldfirst.next;
        N--;

        //如果元素被删除完了，重置last为null
        if (isEmpty()){
            last=null;
        }
        return oldfirst.item;
    }




    private class Node{
        public T item;
        public Node next;

        public Node(T item,Node next){
            this.item=item;
            this.next=next;
        }
    }



    @Override
    public Iterator<T> iterator() {
        return new QIterator();
    }

    private class QIterator implements Iterator{
        private Node n;

        public  QIterator(){
            this.n=head;
        }

        @Override
        public boolean hasNext() {
            return n.next!=null;
        }

        @Override
        public Object next() {
            n=n.next;
            return n.item;
        }
    }

}
